<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="25%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
      style="width: 100%"
    >
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="formData.businessType" placeholder="请选择业务类型" style="width: 100%">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MEIJIA_BUSINESS_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目分类" prop="projectClass">
        <el-select v-model="formData.projectClass" placeholder="请选择项目分类" style="width: 100%">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MEIJIA_PROJECT_CLASS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入项目名称" />
      </el-form-item>

      <el-form-item label="预计服务时间" prop="serverTime">
        <el-input
          v-model="formData.serverTime"
          placeholder="请输入预计服务时间（分钟）"
          oninput="value=value.replace(/^0|[^0-9]/g, '')"
        />
      </el-form-item>
      <el-form-item label="原价" prop="originalPrice">
        <el-input
          v-model="formData.originalPrice"
          placeholder="请输入原价"
          oninput="value=value.replace(/[^\d^\.]+/g, '').replace(/^0+(\d)/, '$1').replace(/^\./, '0.').match(/^\d*(\.?\d{0,2})/g)[0] || ''"
        />
      </el-form-item>
      <el-form-item label="MVIP价格" prop="discountPrice">
        <el-input v-model="formData.discountPrice" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="项目标签" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入项目标签" />
      </el-form-item>
      <el-form-item label="项目描述" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入项目描述" />
      </el-form-item>
      <el-form-item label="图片地址" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleImgSuccess"
          :before-upload="beforeUpload"
          :headers="headers"
        >
          <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ProjectApi from '@/api/meijia/project'
import { watch } from 'vue'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { getAccessToken, getTenantId } from '@/utils/auth'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  businessType: undefined,
  projectLevel: undefined,
  serverTime: undefined,
  originalPrice: undefined,
  discountPrice: undefined,
  imageUrl: undefined,
  tags: undefined,
  remark: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  businessType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }],
  projectClass: [{ required: true, message: '项目分类不能为空', trigger: 'blur' }],
  serverTime: [{ required: true, message: '预计服务时间不能为空', trigger: 'blur' }],
  originalPrice: [{ required: true, message: '原价不能为空', trigger: 'blur' }],
  discountPrice: [{ required: true, message: '折扣价格不能为空', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '图片地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProjectApi.getProject(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProjectApi.ProjectVO
    if (formType.value === 'create') {
      await ProjectApi.createProject(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProjectApi.updateProject(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const url = import.meta.env.VITE_UPLOAD_URL
const headers = ref({
  Authorization: 'Bearer ' + getAccessToken()
})
const handleImgSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.imageUrl = response.data
}
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' ) {
    ElMessage.error('Avatar picture must be JPG PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传照片不能超过5MB!')
    return false
  }
  return true
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    businessType: undefined,
    projectLevel: undefined,
    serverTime: undefined,
    originalPrice: undefined,
    discountPrice: undefined,
    imageUrl: undefined,
    tags: undefined
  }
  formRef.value?.resetFields()
}
// watch(
//   () => deepClone(),
//   (newValue, oldValue) => {
//     console.info(newValue)
//     // newValue 是新的值
//     // oldValue 是旧的值
//     if (!isNaN(newValue)) {
//       formData.discountPrice = formData.originalPrice * 0.8
//     }
//   }
// )
watch(
  () => formData.value.originalPrice,
  (New, Old) => {
    if (!isNaN(New)) {
      formData.value.discountPrice = (New * 0.85).toFixed(2)
    }
  }
)
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
img {
  width: 150px;
}
</style>
